package cn.wmw.xyy.mq.listener;

import cn.wmw.xyy.bo.CourseOrderExtParamsBo;
import cn.wmw.xyy.bo.PayTxLocalBo;
import cn.wmw.xyy.domain.PayFlow;
import cn.wmw.xyy.service.IPayFlowService;
import cn.wmw.xyy.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-pay-order-handle-produce")
@Component
public class PayTxLocalListener implements RocketMQLocalTransactionListener {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IPayFlowService payFlowService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            if (arg == null){
                log.error("报错了！没得参数");
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            PayTxLocalBo payTxLocalBo = JSON.parseObject(JSON.toJSONString(arg), PayTxLocalBo.class);
            // 执行本地事务
            payOrderService.payOrderLocalHandle(payTxLocalBo);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        byte[] bytes = (byte[]) msg.getPayload();
        if (bytes.length == 0){
            return RocketMQLocalTransactionState.ROLLBACK;
        }

        CourseOrderExtParamsBo courseOrderExtParamsBo = JSON.parseObject(new String(bytes, StandardCharsets.UTF_8), CourseOrderExtParamsBo.class);

        PayFlow payFlow = payFlowService.selectByOrderNo(courseOrderExtParamsBo.getOrderNo());

        if (payFlow == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
